//
//  NSString+OCTool.m
//  OCBase
//
//  Created by Duncan on 2023/6/7.
//

#import "NSString+OCTool.h"
#import <AdSupport/ASIdentifierManager.h>

@implementation NSString (OCTool)

/// 判断字符串是否为空
- (BOOL)isEmpty {
    if ((NSNull *)self == [NSNull null]){
        return YES;
    }
    if (self == nil) {
        return YES;
    } else if ([self length] == 0) {
        return YES;
    } else {
        if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
            return YES;
        }
    }
    return NO;
}

#pragma mark ------- App信息 -------

/// 比较版本号大小  线上版本号
+ (BOOL)versionCompareWithVersion:(NSString *)version {
    NSString *app = [[UIDevice appCurrentVersion] stringByReplacingOccurrencesOfString:@"." withString:@""];
    version = [version stringByReplacingOccurrencesOfString:@"." withString:@""];
    if (app.intValue > version.intValue) {
        return YES;
    } else {
        return NO;
    }
}

/// 获取版本号，比如321
+ (NSString *)getAppVersion {
    return [[UIDevice appCurrentVersion] stringByReplacingOccurrencesOfString:@"." withString:@""];
}

#pragma mark ------- 手机设备信息 -------

/// 获取屏幕分辨率
+ (NSString *)getPhoneResolution {
    CGSize screenSize = [UIScreen instancesRespondToSelector:@selector(currentMode)] ? [[UIScreen mainScreen] currentMode].size : CGSizeZero;
    NSString *string = [NSString stringWithFormat:@"%.0f*%.0f", screenSize.width, screenSize.height];
    return string;
}

/// 获取IDFA
+ (NSString *)getIDFAString {
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

/// 获取随机生成的UUID
+ (NSString *)getUUIDString {
    NSString *uuid = [DataStoreService getStringById:kDataStoreUUID fromTable:Device];
    if (kIsEmpty(uuid)) {
        uuid = [UIDevice deviceID];
        [DataStoreService putString:uuid withId:kDataStoreUUID intoTable:Device];
    }
    return uuid;
}

#pragma mark ------- 工具 -------

/// 查找文本内容里包含的手机号，并将中间四位替换为****
+ (NSString *)getHiddenPhoneNumberContentTextUseString:(NSString *)originContentText {
    NSError *error;
    //设置正则规则：第一位是数字1，接下来后边是10位数字
    NSRegularExpression *attachmentExpression = [NSRegularExpression regularExpressionWithPattern:@"1[\\d]{10}"
                                                                                          options:NSRegularExpressionCaseInsensitive error:&error];
    //获取符合条件的结果数组
    NSArray *resultArr = [attachmentExpression matchesInString:originContentText options:0 range:NSMakeRange(0, originContentText.length)];
    if (resultArr.count > 0) {
        //遍历结果数组，替换对应位置的字符串
        for (NSTextCheckingResult *tmpResult in resultArr) {
            NSString *tmpStr = [originContentText substringWithRange:tmpResult.range];
            originContentText = [originContentText stringByReplacingCharactersInRange:tmpResult.range withString:[NSString getHiddenPhoneNumberUseString:tmpStr]];
        }
    }
    return originContentText;
}

/// 替换手机号中间四位为****
+ (NSString *)getHiddenPhoneNumberUseString:(NSString *)originPhoneNumber {
    // 校验长度，防止传入数据不对引起崩溃
    if (originPhoneNumber.length >= 7) {
        return [originPhoneNumber stringByReplacingOccurrencesOfString:[originPhoneNumber substringWithRange:NSMakeRange(3,4)] withString:@"****"];
    } else {
        return originPhoneNumber;
    }
}

// 字符串里超过5位的数字处理
+ (NSString *)getMoreFiveNumberWithContent:(NSString *)content {
    NSError *error;
    //设置正则规则
    NSRegularExpression *attachmentExpression = [NSRegularExpression regularExpressionWithPattern:@"^\\d{5,}$"
                                                                                          options:NSRegularExpressionCaseInsensitive error:&error];
    //获取符合条件的结果数组
    NSArray *resultArr = [attachmentExpression matchesInString:content options:0 range:NSMakeRange(0, content.length)];
    if (resultArr.count > 0) {
        //遍历结果数组，替换对应位置的字符串
        for (NSTextCheckingResult *tmpResult in resultArr) {
            NSString *tmpStr = [content substringWithRange:tmpResult.range];
            DEBUGLOG(@"%@", tmpStr);
            content = [content stringByReplacingCharactersInRange:tmpResult.range withString:[NSString getHiddenFiveNumberString:tmpStr]];
        }
    }
    return content;
}

/// 保留第一位数字，其他都改为****
+ (NSString *)getHiddenFiveNumberString:(NSString *)originNumber {
    // 校验长度，防止传入数据不对引起崩溃
    if (originNumber.length > 1) {
        NSString *changeString = @"";
        NSInteger index = originNumber.length - 1;
        for (int x = 0; x < index; x++) {
            changeString = [changeString stringByAppendingString:@"*"];
        }
        return [originNumber stringByReplacingOccurrencesOfString:[originNumber substringWithRange:NSMakeRange(1, originNumber.length - 1)] withString:changeString];
    } else {
        return originNumber;
    }
}

/// 秒转时间  分秒
+ (NSString *_Nullable)convertTimecode:(int64_t)time {
//    time = (time + 550000) / 1000000;
    int min = (int)time / 60;
    int sec = (int)time % 60;
    if (min >= 10 && sec >= 10)
        return [NSString stringWithFormat:@"%d分%d秒", min, sec];
    else if (min >= 10)
        return [NSString stringWithFormat:@"%d分0%d秒", min, sec];
    else if (sec >= 10)
        return [NSString stringWithFormat:@"0%d分%d秒", min, sec];
    else
        return [NSString stringWithFormat:@"0%d分0%d秒", min, sec];
}

+ (NSString *)getMMSSFromSS:(NSString *)totalTime {

    NSInteger seconds = [totalTime integerValue];
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    return format_time;
}

/// 当文件名为中文时，解决url编码问题
+ (NSString *)URLDecodedString:(NSString *)str {
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    DEBUGLOG(@"decodedString = %@",decodedString);
    return decodedString;
}

/// 判断字符串是否有中文
+ (BOOL)IsChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff) {
            return YES;
        }
    }
    return NO;
}

@end
